package com.shjy.driver.delegate;

import android.app.ActivityManager;
import android.app.Notification;
import android.app.NotificationManager;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.location.LocationManager;
import android.media.Ringtone;
import android.media.RingtoneManager;
import android.net.Uri;
import android.os.Environment;
import android.os.Handler;
import android.support.v4.app.NotificationCompat;
import android.text.TextUtils;
import android.util.Log;
import android.webkit.JavascriptInterface;
import android.webkit.WebView;

import com.android.volley.AuthFailureError;
import com.android.volley.Request;
import com.android.volley.RequestQueue;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.android.volley.toolbox.RequestFuture;
import com.android.volley.toolbox.StringRequest;
import com.android.volley.toolbox.Volley;
import com.shjy.driver.R;
import com.shjy.driver.activity.DetailActivity;
import com.shjy.driver.activity.LoginActivity;
import com.shjy.driver.activity.MainActivity;
import com.shjy.driver.activity.PrintActivity;
import com.shjy.driver.amap.LocationUtil;
import com.shjy.driver.base.BluetoothPrint;
import com.shjy.driver.jg.JGUtil;
import com.shjy.driver.service.LocationService;
import com.shjy.driver.service.VersionUpdateService;
import com.shjy.driver.util.AntUtils;
import com.shjy.driver.util.AppUtil;
import com.shjy.driver.util.BusinesNumberConst;
import com.shjy.driver.util.Const;

import org.json.JSONObject;

import java.io.File;
import java.io.RandomAccessFile;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;

/**
 * Created by ld on 2017/6/29.
 */

public class BaseWebviewDelegate {

    private static final String TAG = "LocationUtil";
    protected Context mContext;
    protected Handler mHandler;
    protected WebView mWebView;
    protected Intent mIntent;

    public BaseWebviewDelegate() {
    }

    public BaseWebviewDelegate(Context context) {
        mContext = context;
    }

    public BaseWebviewDelegate(Context context, WebView webView) {
        mContext = context;
        mWebView = webView;
    }

    public BaseWebviewDelegate(Context context, Handler handler, WebView webView) {
        mContext = context;
        mHandler = handler;
        mWebView = webView;
    }

    /**
     * setCookie
     * @param key
     * @param value
     */
    @JavascriptInterface
    public void setCookie(String key, String value) {
        AppUtil.writeData("set cookie key="+key+" value="+value);
        if(Const.waybillId.equals(key)){
            SharedPreferences sharedPreferences = mContext.getSharedPreferences("cookie", Context.MODE_MULTI_PROCESS);
            SharedPreferences.Editor editor = sharedPreferences.edit();
            try {
                editor.remove(key);
            }catch (Exception ex){
                AppUtil.writeData("set cookie ex="+ex.getMessage());
            }

            AppUtil.writeData("set cookie again key="+key+" value="+value);
            editor.putString(key, value);
            editor.commit();
        }else{
            SharedPreferences sharedPreferences = mContext.getSharedPreferences("cookie", Context.MODE_PRIVATE);
            SharedPreferences.Editor editor = sharedPreferences.edit();

            editor.putString(key, value);
            editor.commit();
        }



        if(Const.KEY_TOKEN.equals(key)){
            SharedPreferences sharedPreferences = mContext.getSharedPreferences("cookie", Context.MODE_MULTI_PROCESS);
            SharedPreferences.Editor editor = sharedPreferences.edit();

            try {
                editor.remove(key);
            }catch (Exception ex){
                AppUtil.writeData("set cookie ex="+ex.getMessage());
            }

            editor.putString(key, value);
            editor.commit();
        }

        // 极光推送设置别名
        if (TextUtils.equals(key, Const.KEY_PHONE)) {
            JGUtil.setAlias(mContext);
        }
    }

    /**
     * setCookie
     * @param key
     */
    @JavascriptInterface
    public void removeCookie(String key) {
        AppUtil.writeData("remove cookie key="+key);
        if(Const.waybillId.equals(key)){
            SharedPreferences sharedPreferences = mContext.getSharedPreferences("cookie", Context.MODE_MULTI_PROCESS);
            SharedPreferences.Editor editor = sharedPreferences.edit();
            try {
                editor.remove(key);
            }catch (Exception ex){
                AppUtil.writeData("remove cookie ex="+ex.getMessage());
            }

            AppUtil.writeData("remove cookie again key="+key);
            editor.commit();
        }
    }

    @JavascriptInterface
    public String startPrint(final String billId,final String totalFee,final String placeDate,final String unloadDate
            ,final String distance,final String startFee,final String waitingTime,final String vehicleNum,
                             final String specialFee,final String hignRoadFee,final String driverNumber){
        String msg = "";
        try {
            String blueToothAddr = AntUtils.getStringAttr(mContext, BusinesNumberConst.CONN_BLUE_TOOTH_ADDR);
            if (TextUtils.isEmpty(blueToothAddr)) {
                //showMessage("没有设置打印机,请到工具-打印机设置中去设置打印机!");
                msg = "没有设置打印机,请到工具-打印机设置中去设置打印机!";
            } else {
                BluetoothPrint bluetoothPrint = null;
                SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
                SimpleDateFormat simpleDayFormat = new SimpleDateFormat("yyyy-MM-dd");
                SimpleDateFormat simpleHourFormat = new SimpleDateFormat("HH:mm");
                try {
                    bluetoothPrint = new BluetoothPrint((DetailActivity) mContext, mHandler, blueToothAddr);
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
                if (bluetoothPrint == null) {
                    try {
                        bluetoothPrint = new BluetoothPrint((MainActivity) mContext, mHandler, blueToothAddr);
                    } catch (Exception ex) {
                        ex.printStackTrace();
                    }
                }
                StringBuffer tvResult = new StringBuffer();
//            tvResult.append("\r\n");"        " +


                tvResult.append( vehicleNum + "\n");
                tvResult.append( driverNumber + "\n");
                tvResult.append( simpleDayFormat.format(simpleDateFormat.parse((placeDate))) + "\n");
                tvResult.append( simpleHourFormat.format(simpleDateFormat.parse((placeDate))) + "\n");
                tvResult.append( simpleHourFormat.format(simpleDateFormat.parse((unloadDate))) + "\n");
                tvResult.append( startFee+"元" + "\n");
                tvResult.append( distance+"km" + "\n");
                tvResult.append( AntUtils.secToTime(Integer.parseInt(waitingTime)) + "\n");
                tvResult.append( totalFee+"元" + "\n");
                tvResult.append( specialFee+"元" + "      "+hignRoadFee+"元\n");
                bluetoothPrint.connectedSend(tvResult.toString());
                msg = "开始打印!";
            }
        }catch (Exception ex){
            ex.printStackTrace();
        }
        return  msg;
    }

    /**
     * initFirtLoad
     * @param driverUuid
     */
    @JavascriptInterface
    public void initFirtLoad(String driverUuid) {

        SharedPreferences sharedPreferencesFirst = mContext.getSharedPreferences("driver", Context.MODE_MULTI_PROCESS);
        SharedPreferences.Editor editor = sharedPreferencesFirst.edit();
        editor.remove("firstLoad_"+driverUuid);
        editor.commit();
    }

    /**
     * getCookie
     * @param key
     * @return value
     */
    @JavascriptInterface
    public String getCookie(String key) {
        SharedPreferences sharedPreferences = mContext.getSharedPreferences("cookie", Context.MODE_PRIVATE);
        return sharedPreferences.getString(key, "");
    }

    /**
     * gotoPrint
     * @return value
     */
    @JavascriptInterface
    public void gotoPrint() {
        //mWebView.stopLoading();
        Intent intent = new Intent(mContext, PrintActivity.class);
        mContext.startActivity(intent);
    }

    @JavascriptInterface
    public void checkServiceManual() {
        // 检查Service状态
        boolean isServiceRunning = false;
        ActivityManager manager = (ActivityManager) mContext
                .getSystemService(Context.ACTIVITY_SERVICE);
        for (ActivityManager.RunningServiceInfo service : manager
                .getRunningServices(Integer.MAX_VALUE)) {
            if ("com.shjy.driver.service.LocationService".equals(service.service
                    .getClassName()))// Service的类名
            {
                isServiceRunning = true;
                Log.e("mayi", "http   runing...");
            }

        }
        if (!isServiceRunning) {
            try{
                initData("restart Location service in delegate class");
            }catch (Exception ex){
                ex.printStackTrace();
            }
            Intent i = new Intent(mContext, LocationService.class);
            mContext.startService(i);
        }
    }

    private static void initData(String text) {
        String filePath = Environment.getExternalStorageDirectory().getAbsolutePath() + "/Android/data/com.shjy.driver/files/Download/";
        String fileName = "";
        try {
            fileName = "log-"+formatDate(new Date())+".txt";
        }catch (Exception ex){
            ex.printStackTrace();
        }

        writeTxtToFile(text, filePath, fileName);
    }

    private static  String formatDate(Date date) throws Exception{
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        return sdf.format(date);
    }

    // 将字符串写入到文本文件中
    public static void writeTxtToFile(String strcontent, String filePath, String fileName) {
        //生成文件夹之后，再生成文件，不然会出错
        makeFilePath(filePath, fileName);

        String strFilePath = filePath+fileName;
        // 每次写入时，都换行写
        String strContent = strcontent + "\r\n";
        try {
            File file = new File(strFilePath);
            if (!file.exists()) {
                Log.d("TestFile", "Create the file:" + strFilePath);
                file.getParentFile().mkdirs();
                file.createNewFile();
            }
            RandomAccessFile raf = new RandomAccessFile(file, "rwd");
            raf.seek(file.length());
            raf.write(strContent.getBytes());
            raf.close();
        } catch (Exception e) {
            Log.e("TestFile", "Error on write File:" + e);
        }
    }

    // 生成文件
    public static File makeFilePath(String filePath, String fileName) {
        File file = null;
        makeRootDirectory(filePath);
        try {
            file = new File(filePath + fileName);
            if (!file.exists()) {
                file.createNewFile();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return file;
    }

    // 生成文件夹
    public static void makeRootDirectory(String filePath) {
        File file = null;
        try {
            file = new File(filePath);
            if (!file.exists()) {
                file.mkdir();
            }
        } catch (Exception e) {
            Log.i("error:", e+"");
        }
    }

    /**
     * 获取定位信息
     * @return value
     */
    @JavascriptInterface
    public String getLocation() {
        Map<String, String> resultMap = LocationUtil.getLocation(mContext);
        return resultMap.toString();
    }

    /**
     * 获取定位信息
     * @return value
     */
    @JavascriptInterface
    public String getLocationIndex() {
        Map<String, String> resultMap = LocationUtil.getLocationIndex(mContext);
        return resultMap.toString();
    }

    /**
     * 获取定位信息
     * @return value
     */
    @JavascriptInterface
    public String getCurrentLocation() {

        return getLocation();
    }

    /**
     * 获取和客户的距离信息
     * @return value
     */
    @JavascriptInterface
    public String getCurrentDistance(String latClient,String lonClient) {
        String distance = "2";
        try {
            JSONObject jsonObject = new JSONObject(getLocation());
            String lat = jsonObject.getString("lat");
            String lon = jsonObject.getString("lon");
            distance = AppUtil.getDistance(latClient,lonClient,lat,lon)+"";
        }catch (Exception ex){
            ex.printStackTrace();
        }
        return distance;
    }

    @JavascriptInterface
    public void call(String tel) {
        Intent intent = new Intent();
        intent.setAction(Intent.ACTION_DIAL);
        intent.setData(Uri.parse("tel:" + tel));
        mContext.startActivity(intent);
    }

    @JavascriptInterface
    public void playStartBid() {
        NotificationManager nm = (NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE);
        Uri ringUri = Uri.parse("android.resource://" + mContext.getPackageName() + "/"+ R.raw.startbid);//RingtoneManager.getDefaultUri(ringType);
        Notification notification = new NotificationCompat.Builder(mContext)
                .setTicker("开始接单").setSound(ringUri)
                .setContentTitle("开始接单").setContentText("开始接单").setSound(ringUri).build();
        Ringtone r = RingtoneManager.getRingtone(mContext, ringUri);
        r.play();
    }

    @JavascriptInterface
    public void playEndBid() {
        NotificationManager nm = (NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE);
        Uri ringUri = Uri.parse("android.resource://" + mContext.getPackageName() + "/"+ R.raw.endbid);//RingtoneManager.getDefaultUri(ringType);
        Notification notification = new NotificationCompat.Builder(mContext)
                .setTicker("开始接单").setSound(ringUri)
                .setContentTitle("开始接单").setContentText("开始接单").setSound(ringUri).build();
        Ringtone r = RingtoneManager.getRingtone(mContext, ringUri);
        r.play();
    }

    @JavascriptInterface
    public void playTishi() {
        NotificationManager nm = (NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE);
        Uri ringUri = Uri.parse("android.resource://" + mContext.getPackageName() + "/"+ R.raw.tishi);//RingtoneManager.getDefaultUri(ringType);
        Notification notification = new NotificationCompat.Builder(mContext)
                .setTicker("开始接单").setSound(ringUri)
                .setContentTitle("开始接单").setContentText("开始接单").setSound(ringUri).build();
        Ringtone r = RingtoneManager.getRingtone(mContext, ringUri);
        r.play();
    }

    @JavascriptInterface
    public String getVersion() {
        String versionName = "1.0";
        try {
            PackageInfo packageInfo = mContext.getApplicationContext().getPackageManager().getPackageInfo(mContext.getPackageName(), 0);
            versionName = packageInfo.versionName;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
        return versionName;
    }

    @JavascriptInterface
    public String isGPSAvailable() {
        LocationManager locationManager = (LocationManager)mContext.getSystemService(Context.LOCATION_SERVICE);
        boolean gps = locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER);
        if(gps){
            return "1";
        }
        NotificationManager nm = (NotificationManager) mContext.getSystemService(Context.NOTIFICATION_SERVICE);
        Uri ringUri = Uri.parse("android.resource://" + mContext.getPackageName() + "/"+R.raw.gps);//RingtoneManager.getDefaultUri(ringType);
        Notification notification = new NotificationCompat.Builder(mContext)
                .setTicker("请打开GPS").setSound(ringUri)
                .setContentTitle("请打开GPS").setContentText("请打开GPS").setSound(ringUri).build();
//        nm.notify(R.string.app_name,notification);
        Ringtone r = RingtoneManager.getRingtone(mContext, ringUri);
        r.play();
        return "0";
    }

    @JavascriptInterface
    public String checkVersion() {

        String result = "0";
        String currentVersion = getVersion();

        //String url = "http://139.224.80.49/shjy/fetchVersion.htm?type=1";
        //String url = "http://101.200.228.33/shjy/fetchVersion.htm?type=1";
        String url = "http://www.65376537.net/jybjwechat/fetchVersion.htm?type=1";
        RequestFuture<String> future = RequestFuture.newFuture();
        StringRequest stringRequest = new StringRequest(url,future,future);
        RequestQueue requestQueue = Volley.newRequestQueue(mContext);
        requestQueue.add(stringRequest);
        try {
            String request = future.get();
            future.get(3000, TimeUnit.SECONDS);//添加请求超时

            JSONObject jsonObject = new JSONObject(request);
            String version = jsonObject.getString("version");
            String downloadUrl = jsonObject.getString("url");
            long versionL = Long.parseLong(version.substring(1));
            long currentVersionL = Long.parseLong(currentVersion.substring(1));

            if (versionL>currentVersionL) {
                result = version;
                downloadUrl += "?id="+new Date().getTime();
                SharedPreferences sharedPreferences = mContext.getSharedPreferences("versonUpdate", Context.MODE_PRIVATE);
                SharedPreferences.Editor editor = sharedPreferences.edit();
                editor.putString("downloadUrl", downloadUrl);
                editor.commit();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        return result;
    }

    @JavascriptInterface
    public void updatePhoneInfo() {

        String url = Const.DOMAIN + "driver/phoneInfo.htm";
        SharedPreferences sharedPreferences = mContext.getSharedPreferences("cookie", Context.MODE_MULTI_PROCESS);
        final String driverUuid = sharedPreferences.getString(Const.KEY_TOKEN, "");
        RequestQueue requestQueue = Volley.newRequestQueue(mContext);

        StringRequest stringRequest = new StringRequest(Request.Method.POST, url, new Response.Listener<String>() {
            @Override
            public void onResponse(String s) {
                Log.d(TAG, "onResponse " + s);
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                Log.d(TAG, "onErrorResponse " + volleyError.getMessage());
            }
        }) {
            @Override
            protected Map<String, String> getParams() throws AuthFailureError {
                Map<String, String> map = new HashMap<String, String>();
                try {

                    map.put("driverUuid", driverUuid);
                    map.put("deviceNo", AppUtil.getDeviceBrand());
                    map.put("deviceModel", AppUtil.getSystemModel());
                }catch (Exception ex){
                    ex.printStackTrace();
                }
                //Log.d(TAG, "getParams " + map);
                return map;
            }
        };

        requestQueue.add(stringRequest);
    }

    @JavascriptInterface
    public void updateApp() {

        mContext.startService(new Intent(mContext, VersionUpdateService.class));
    }
}
